package com.MarkToTop.main;

import com.MarkToTop.util.Constant;
import com.MarkToTop.util.MusicUtil;
import sun.audio.AudioStream;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import static com.MarkToTop.util.Constant.*;

/**
 * MarkWang 版权所有 © Copyright 2020
 *
 * @CreateDate: Created in 2020-06-22 11:21
 * @Author: MarkToTop -(づ｡◕‿‿◕｡)づ
 * @Description:
 */
public class GameFrame extends JFrame implements Runnable {
    //游戏的状态
    private static int gameState;
    public static final int STATE_READY = 0;
    public static final int STATE_PLAY = 1;
    public static final int STATE_OVER = 2;
    //创建游戏背景对象
    private GameBackGround backGround;
    //创建游戏前景对象
    private GameFrontGround frontGround;
    //创建碰撞层对象
    private GameBarrierLayer barrierLayer;
    //创建小鸟对象
    private Bird bird;
    //绘制游戏开始GameReady（）
    private GameReady gameReady;
    //音频
    private MusicUtil musicUtil;

    /**
     *双缓冲机制-——单独创建一个图片(大小和窗口一样)，将所有要绘制的东西，全部绘制到这张图片上，再由这张图片全部一次性绘制在屏幕上
     * 解决屏幕因为一次绘制不完，而导致屏幕闪烁的问题
     */
    private BufferedImage bufferImage = new BufferedImage(Frame_Width,Frame_Height,BufferedImage.TYPE_4BYTE_ABGR);


    /**
     * 构造方法中进行初始化
     */
    public GameFrame() {
        initGame();
        initFrame();

        //启动线程，不断 刷新窗口
        new Thread(this).start();
    }

    /**
     * 初始化窗体
     */
    private void initFrame() {
        //大小、可见
        setSize(Frame_Width, Frame_Height);
        setVisible(true);
        //标题
        setTitle(GAME_TITLE);
        //启动显示位置-屏幕中央
        setLocationRelativeTo(null);
        //窗口大小不可变
        setResizable(false);
        //窗口关闭事件 ->关闭窗口弹出提示
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                int exi = JOptionPane.showConfirmDialog(null, "要退出该程序吗？", "亲爱的小朋友", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (exi != JOptionPane.YES_OPTION) return;
                System.exit(0);
            }
        });

        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);  //设置用户在此窗体上发起 "close" 时默认执行的操作
        //键盘监听，内部类
        addKeyListener(new MyKeyListener());
    }


    //键盘监听 -空格的实现
    class MyKeyListener implements KeyListener {
        @Override
        public void keyTyped(KeyEvent e) { }
        /**
         * 处理按键被按下的事件
         */
        @Override
        public void keyPressed(KeyEvent e) {
            //捕获按键的虚拟键值
            int keyCode = e.getKeyCode();
            switch (gameState){
                case STATE_READY:
                    if(keyCode == KeyEvent.VK_SPACE){
                        setGameState(STATE_PLAY);
                        //开始计时
                        bird.startTiming();
                    }
                    break;
                case STATE_PLAY:
                    //当按下空格键时，向上飞
                    if(keyCode == KeyEvent.VK_SPACE){
                        bird.fly();
                    }
                    break;
                case STATE_OVER:
                    if(keyCode == KeyEvent.VK_SPACE){
                        resetGame();
                    }
                        break;
            }
        }
        /**
         * 处理按键被松开的事件
         */
        @Override
        public void keyReleased(KeyEvent e) {
            //捕获按键的虚拟键值
            int keyCode = e.getKeyCode();
            switch (gameState){
                case STATE_READY:
                    break;
                case STATE_PLAY:
                    //当释放空格键时，向下飞
                    if(keyCode == KeyEvent.VK_SPACE){
                        bird.down();
                    }
                    break;
            }
        }
    }

    private void resetGame(){
        setGameState(STATE_READY);
        barrierLayer.reset();  //清空障碍物
        bird.reset();
        MusicUtil.load();
    }

    /**
     * 初始化游戏内容
     */
    private void initGame() {
        backGround = new GameBackGround();
        frontGround = new GameFrontGround();
        barrierLayer = new  GameBarrierLayer();
        bird = new Bird();
        musicUtil = new MusicUtil();
        gameReady = new GameReady();
        MusicUtil.load(); //加载音频
        try {
            musicUtil.BGMusic();
        } catch (Exception e) {
            e.printStackTrace();
        }
        setGameState(STATE_READY);
    }

    /**
     * 所有在游戏中要绘制的东西，都要调用此方法进行绘制
     * @param g
     */
    @Override
    public void paint(Graphics g) {
        /**
         * 1-得到bufferImage图片的画笔
         */
        Graphics buffG = bufferImage.getGraphics();
        /**
         * 2-将景物全部绘制在 bufferImage 图片上
         */
        //画背景
        backGround.draw(buffG);
        if(gameState == STATE_READY){//游戏准备阶段
            //画鸟
            bird.drawBagin(buffG);
            gameReady.draw(buffG);
        }else {  // 游戏开始
            //画碰撞层
            barrierLayer.draw(buffG,bird);
            //画鸟
            bird.draw(buffG);
            //画前景
            frontGround.draw(buffG);
        }
        /**
         * 3-最终将 bufferImage 进行绘制在屏幕上
         */
        g.drawImage(bufferImage,0,0,null);
    }

    @Override
    public void run() {
        while (true){
            //通过调用repaint(),让JVM调用 paint() 方法进行绘制
            //一秒钟30次  FPS  (Frame Per Second)
            repaint();
            try {
                Thread.sleep(GAME_INTERAVL);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static int getGameState() {
        return gameState;
    }

    public static void setGameState(int gameState) {
        GameFrame.gameState = gameState;
    }
}
